﻿/*----------------------------------------------------------------
 * 
 * 版权所有：同程网络科技股份有限公司 Copyright (C) 2013
 * 
 * 文件名：TimingModule.cs
 * 文件功能描述：
 * 
 * 
 * 作 者：张强5374
 * 邮 箱：zq5374@17u.cn
 * 日 期：2013-07-08 13:28:49
 * 
 * 
 * 修改标识： Author
 * 修改描述： 相关描述
 * 
 * ---------------------------------------------------------------- */

using System;
using System.Diagnostics;
using System.Web;
using System.Web.Mvc;

namespace WebClientPlatform.HttpModules
{
    public class TimingModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnBeginRequest;
            context.EndRequest += OnEndRequest;
        }


        private void OnBeginRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.IsLocal && HttpContext.Current.IsDebuggingEnabled)
            {
                var stopwatch = new Stopwatch();
                HttpContext.Current.Items["Stopwatch"] = stopwatch;
                stopwatch.Start();
            }
        }

        private void OnEndRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.IsLocal && HttpContext.Current.IsDebuggingEnabled)
            {
                Stopwatch stopwatch =
                  (Stopwatch)HttpContext.Current.Items["Stopwatch"];
                stopwatch.Stop();

                TimeSpan ts = stopwatch.Elapsed;
                string elapsedTime = String.Format("{0}ms", ts.TotalMilliseconds);

                //HttpContext.Current.Response.Write("<p>" + elapsedTime + "</p>");


                HttpApplication appliction = sender as HttpApplication;
                if (appliction != null)
                {
                    // var p =  appliction.Context.CurrentHandler;


                    //var mvcHandler = (appliction.Context.CurrentHandler as MvcHandler);
                    //if (mvcHandler != null)
                    //{
                    //    var dic = mvcHandler.RequestContext.RouteData.Values;
                    //    foreach (var item in dic)
                    //    {
                    //        HttpContext.Current.Response.Write("<p>" + item.Key + ":" + item.Value + "</p>");
                    //    }
                    //}



                    // HttpContext.Current.Response.Write(appliction.Context.Request.Url.AbsoluteUri);
                }

            }
        }

        public void Dispose()
        {

        }
    }
}